<?php

namespace liketp\view;

use liketp\contract\ViewInterface;
use liketp\exception\FileNotFoundException;

abstract class BaseView implements ViewInterface
{
    protected $data = [];
    protected $tpl = '';
    protected $viewPath = '';
    protected $tplContent = '';
    protected $ext = '.html';

    public function tpl(string $tpl, bool $isContent = true)
    {
        if ($isContent) {
            $this->tplContent = $tpl;
        } else {
            $this->tpl = $this->viewPath . $tpl . $this->ext;
            if (file_exists($this->tpl)) {
                $this->tplContent = file_get_contents($this->tpl);
            } else {
                throw new FileNotFoundException($this->tpl);
            }
        }
        return $this;
    }

    public function assign($key, $val = null)
    {
        if (is_array($key)) {
            $this->data = array_merge($this->data, $key);
        } else if (is_string($key)) {
            $this->data[$key] = $val;
        }
        return $this;
    }

    public function data(array $data, bool $merge = false)
    {
        if ($merge) {
            $this->data = array_merge($this->data, $data);
        } else {
            $this->data = $data;
        }
        return $this;
    }

    abstract public function render(): string;
}
